package com.flower.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.flower.pojo.PageBean;
import com.flower.pojo.Product;
import com.flower.service.IProductService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 商品模块
 */

@Controller
public class ProductController {

    @Resource(name = "productService")
    private IProductService iProductService;

    /**
     * 查询热门、最新商品和特价商品
     */
    @RequestMapping("/findHotNewProduct.do")
    public String findHotNewProduct(Model model){
        List<Product> hotProductList = iProductService.findHotProduct();
        List<Product> newProductList = iProductService.findNewProduct();
        List<Product> bargainProductList = iProductService.findBargainProduct();
        // Model(request)
        model.addAttribute("HOT_PRODUCT_LIST", hotProductList);
        model.addAttribute("NEW_PRODUCT_LIST", newProductList);
        model.addAttribute("BARGAIN_PRODUCT_LIST", bargainProductList);
        // 转发（request域）
        return "index";
    }

    /**
     * 分页 -> 根据类别编号，查询所有商品
     * int类型不能用于判断，需要改为Integer
     */
    @RequestMapping("/findAllProductByCid.do")
    public String findAllProductByCid(int cid, Integer currPageNO,
    		Model model, HttpServletRequest request){
        //判断当前页是否为空，若为空，赋予1
        if (currPageNO == null){
            currPageNO = 1;
        }
        //1.通过类别编号获取分页的所有商品
        PageBean<Product> pageBean = iProductService.findAllProductByCid(cid, currPageNO);
        model.addAttribute("PAGEBEAN", pageBean);
        
        //2.获取曾经浏览过的记录
        Cookie[] cookies = request.getCookies();
        
        String imgs[] = null;
        for(int i = 0; cookies != null && i < cookies.length; i++){
        	if(cookies[i].getName().equals("productHistory")){
        		imgs = cookies[i].getValue().split("\\,");
        	}
        }
        model.addAttribute("IMGS", imgs);
        
        return "product_list";
    }

    /**
     * 根据商品编号查询商品详情
     * @param pid
     */
    @RequestMapping("/findProductByPid.do")
    public String findProductByPid(int pid, Model model,
    		HttpServletRequest request, HttpServletResponse response){
    	//1.显示商品的详细信息
        Product product = iProductService.findProductByPid(pid);
        //封装在session中
        request.getSession().setAttribute("PRODUCT", product);
        //model.addAttribute("PRODUCT", product);
        
        //2.创建cookie，回写给浏览器
        String cookieValue = buidCookie(pid, request);
        //cookieValue:
        Cookie cookie = new Cookie("productHistory", cookieValue);
        //设置有效期一个月
        cookie.setMaxAge(1*30*24*60*60);
        response.addCookie(cookie);
        
        return "product_info";
    }

	private String buidCookie(int pid, HttpServletRequest request) {
		// productHistory=null      1       1
		// productHistory=2,3,1     1       1,2,3
		// productHistory=2,3,4     1       1,2,3
		// productHistory=2,3       1       1,2,3
		
		String productHistory = null;
		Cookie[] cookies = request.getCookies();
		
		for(int i = 0; cookies != null & i < cookies.length; i++){
        	if(cookies[i].getName().equals("productHistory")){
        		productHistory = cookies[i].getValue();
        	}
		}
		
		String msg = iProductService.findProductByPid(pid).getPimage();
		if(productHistory == null){
			return msg;
		}
		
		LinkedList<String> list = new LinkedList<String>(Arrays.asList(productHistory.split("\\,")));
		if(list.contains(msg)){
			list.remove(msg);
		}else {
			if(list.size() >= 7){
				list.removeLast();
			}
		}
		list.addFirst(msg);
		
		StringBuffer buffer = new StringBuffer();
		for(String proudct: list){
			buffer.append(proudct + ",");
		}
		
		return buffer.deleteCharAt(buffer.length()-1).toString();
	}

}
